package com.atlige.gzmallssoclient.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;

/**
 * @author: Jeremy lI
 * @description:
 * @date: created in 2021/6/5 11:09
 */
@Controller
public class HelloController {
    @Value("${sso.server.url}")
    String ssoServerUrl;
    /**
     * 无需登录就可访问
     * @return
     */
    @GetMapping("/hello")
    @ResponseBody
    public String Hello(){
        return "hello";
    }

    @GetMapping("/employees")
    public String employees(Model model, HttpSession session,
                            @RequestParam(value = "token", required = false) String token){
        if (token != null){
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> entity = restTemplate.getForEntity("http://ssoserver.com:8080/userInfo?token=" + token,
                    String.class);
            if (entity.getBody() != null){
                session.setAttribute("loginUser", entity.getBody());
            }
        }
        Object loginUser = session.getAttribute("loginUser");
        if (loginUser == null){
            // 没登陆，跳转到登陆
            return "redirect:" + ssoServerUrl + "?redirect_url=http://client1.com:8081/employees";
        }else {
            ArrayList<String> list = new ArrayList<>();
            list.add("张三");
            list.add("李四");
            list.add("王五");
            model.addAttribute("emps", list);
            return "employees";
        }

    }

}
